package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.StatusInfo;
import com.lkd.contract.VmStatusContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.security.auth.login.LoginException;
import java.io.IOException;


@Component
@Topic(TopicConfig.VMS_STATUS_TOPIC)
@Slf4j
public class VMStatusHandler implements MsgHandler {

    @Autowired
    private VMService vmService;

    @Autowired
    private TaskService taskService;
    @Override
    public void process(String jsonMsg) throws IOException {
        VmStatusContract byJson = JsonUtil.getByJson(jsonMsg, VmStatusContract.class);
        if (byJson == null || StringUtils.isEmpty(byJson.getStatusInfo())) return;
        //如果为非正常状态，则创建维修工单
        if (byJson.getStatusInfo().stream().anyMatch(statusInfo -> statusInfo.isStatus() == false)) {
            try {
                //根据售货机编号，查询售货机
                VmVO vmVO = vmService.getVMInfo(byJson.getInnerCode());
                //查询最少工单量用户
                int leastUserId = taskService.getLeastUser(vmVO.getRegionId(), true);
                //创建工单对象
                TaskViewModel task = new TaskViewModel();
                task.setAssignorId(-1);
                task.setUserId(leastUserId);
                task.setCreateType(0);
                task.setInnerCode(byJson.getInnerCode());
                task.setProductType(VMSystem.TASK_TYPE_REPAIR);
                task.setDesc("自动维修工单");
                taskService.addTask(task);
            } catch (LoginException e) {
                log.info("创建自动维修工单失败，msg is:"+jsonMsg);
            }
        }
    }
}
